package com.ssyshop.info.activity.home;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.map.MapStatus;
import com.ssyshop.info.R;
import com.ssyshop.info.adapter.MyFragmentPageAdapter;
import com.ssyshop.info.fragment.GoodsCommentFragment;
import com.ssyshop.info.fragment.GoodsInfoFragment;
import com.ssyshop.info.https.OkHttpClientManager;
import com.ssyshop.info.model.Attrs;
import com.ssyshop.info.model.Goods;
import com.ssyshop.info.utils.BitmapCache;
import com.ssyshop.info.utils.Config;
import com.ssyshop.info.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GoodsInfoActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除actionbar
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_goods_info);
        initView();
        initData();
        initEvent();
    }

    private ImageView btn_back;
    private RadioGroup details_ra;
    private RelativeLayout goods_cart_msg;
    private ImageView show_msg;
    private TextView btn_shop, btn_service;
    private CheckBox btn_cellect;
    private TextView create_cart, buy_now;
    private ViewPager goods_viewpager;
    private Goods goods;
    private FragmentManager manager;
    private List<Fragment> list = new ArrayList<>();
    private List<Attrs> list_attrs = new ArrayList<>();
    private TextView tv_line;
    private LinearLayout.LayoutParams layoutParams;// 布局参数
    private RequestQueue queue;//利用ImageRequest对象简单、方便地进行网络图片的获取
    private ImageLoader imageLoader;//用于获取或缓存图片
    private void initView() {
        btn_back = (ImageView) findViewById(R.id.btn_back);
        details_ra = (RadioGroup) findViewById(R.id.details_ra);
        goods_cart_msg = (RelativeLayout) findViewById(R.id.goods_cart_msg);
        show_msg = (ImageView) findViewById(R.id.show_msg);
        btn_shop = (TextView) findViewById(R.id.btn_shop);
        btn_service = (TextView) findViewById(R.id.btn_service);
        btn_cellect = (CheckBox) findViewById(R.id.btn_cellect);
        create_cart = (TextView) findViewById(R.id.create_cart);
        buy_now = (TextView) findViewById(R.id.buy_now);
        goods_viewpager = (ViewPager) findViewById(R.id.goods_viewpager);
        tv_line = (TextView) findViewById(R.id.tv_line);
    }

    private void initData() {
        queue = Volley.newRequestQueue(this);
        imageLoader = new ImageLoader(queue, new BitmapCache());
        try {
            goods = (Goods) getIntent().getSerializableExtra("goods");
        } catch (Exception e) {
            goods = null;
            e.printStackTrace();
        }
        GetAttrs getAttrs = new GetAttrs();
        getAttrs.execute(goods.getGoods_id());
        GoodsInfoFragment fragment_1 = new GoodsInfoFragment();
        GoodsCommentFragment fragment_2 = new GoodsCommentFragment();
        list.add(fragment_1);
        list.add(fragment_2);
        manager = getSupportFragmentManager();
        goods_viewpager.setAdapter(new MyFragmentPageAdapter(manager, list));
        if (goods != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("goods", goods);
            fragment_1.setArguments(bundle);

        } else {//数据没有传过来
            finish();
        }
    }

    private void initEvent() {
        btn_back.setOnClickListener(this);
        goods_cart_msg.setOnClickListener(this);
        btn_shop.setOnClickListener(this);
        btn_service.setOnClickListener(this);
        btn_cellect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });
        create_cart.setOnClickListener(this);
        buy_now.setOnClickListener(this);
        details_ra.setOnCheckedChangeListener(changeListener);
        goods_viewpager.addOnPageChangeListener(pageChangeListener);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.goods_cart_msg:

                break;
            case R.id.btn_shop:

                break;
            case R.id.btn_service:

                break;
            case R.id.create_cart://加入购物车
                showBomtomDialog();
                break;
            case R.id.buy_now:

                break;
        }
    }


    //商品参数底部弹出
    private int number = 1;
    private void showBomtomDialog() {
        final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.item_bottom_2, null);
        contentView.findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        contentView.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });
        NetworkImageView goods_img = contentView.findViewById(R.id.goods_img);
        TextView goods_price = contentView.findViewById(R.id.goods_price);
        TextView goods_number = contentView.findViewById(R.id.goods_number);
        TextView btn_minus = contentView.findViewById(R.id.mycar_number_minus);
        final TextView buy_number = contentView.findViewById(R.id.mycar_goods_number);
        TextView btn_add = contentView.findViewById(R.id.mycar_number_add);
        RecyclerView re_attr_list = contentView.findViewById(R.id.re_attr_list);
        goods_img.setDefaultImageResId(R.mipmap.pic_zwt_2);
        goods_img.setErrorImageResId(R.mipmap.pic_zwt_2);
        goods_img.setImageUrl(Config.URL_SERVER+goods.getGoods_thumb(),imageLoader);
        goods_price.setText(goods.getShop_price());
        goods_number.setText(goods.getGoods_number());
        buy_number.setText(number + "");
        btn_minus.setOnClickListener(new View.OnClickListener() {//减少选择的商品数量
            @Override
            public void onClick(View v) {
                number--;
                if (number < 0) {
                    number = 0;
                    Toast.makeText(GoodsInfoActivity.this, "购买数量不能小于0", Toast.LENGTH_SHORT).show();
                } else
                    buy_number.setText(number + "");
            }
        });
        btn_add.setOnClickListener(new View.OnClickListener() {//添加选择的商品数量
            @Override
            public void onClick(View v) {
                number++;
                if (number >= Integer.parseInt(goods.getGoods_number())) {
                    number = Integer.parseInt(goods.getGoods_number());
                    Toast.makeText(GoodsInfoActivity.this, "购买数量不能大于库存", Toast.LENGTH_SHORT).show();
                } else
                    buy_number.setText(number + "");
            }
        });



        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.height = getResources().getDisplayMetrics().heightPixels * 2 / 3;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    /**
     * 监听viewPager页面
     */
    ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        /*
        当页面在滑动的时候会调用此方法，在滑动被停止之前
        position：当前页面，即你点击滑动的页面
        positionOffset：当前页面偏移的百分比
        positionOffsetPixels：当前页面偏移的像素位置
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // 获取tvLine的左边距
            layoutParams = (LinearLayout.LayoutParams) tv_line.getLayoutParams();
            // 说明它有偏移了
            if (layoutParams != null && positionOffset != 0) {
                layoutParams.leftMargin = (int) ((position + positionOffset) * layoutParams.width);
                tv_line.setLayoutParams(layoutParams);// 具有新的layoutMargin的layoutParams
            }
        }

        // 此方法是页面跳转完后得到调用
        @Override
        public void onPageSelected(int position) {
            RadioButton rb = (RadioButton) details_ra.getChildAt(position);
            rb.setChecked(true);
        }

        /*
        此方法是在状态改变的时候调用，其中state这个参数有三种状态（0，1，2）
        state==1:正在滑动   state==2:滑动完毕了   state==0:什么都没有做
        页面滑动时，state变化顺序：1--2--0
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    /**
     * 监听对应ViewPager的单选框
     */
    RadioGroup.OnCheckedChangeListener changeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.rb1:
                    goods_viewpager.setCurrentItem(0);
                    break;
                case R.id.rb2:
                    goods_viewpager.setCurrentItem(1);
                    break;
            }
        }
    };

    /**
     * 查询商品的属性
     */
    class GetAttrs extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            Log.i("goods_id", strings[0]);
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.goods.attr.list.get&goods_id=" + strings[0];
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null)
                return;
            try {
                JSONObject object = new JSONObject(s);
                Log.i("res", object.toString());
                if (object.getString("result").equals("success")) {
                    JSONObject object1 = object.getJSONObject("info");
                    list_attrs = Tools.fromJsonList(object1.getString("list"), Attrs.class);
                    goods.setAttrses(list_attrs);
                } else {//查无数据
                    goods.setAttrses(null);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


}
